import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import MainLayout from '../../../components/MainLayout';
import PageHeader from './components/PageHeader';
import CreateForm from './components/CreateForm';
import HelpSection from './components/HelpSection';
import networkService from '../../../services/network';
import Toast from '../../../components/Toast';
import './CreateNetwork.css';

const CreateNetwork = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [showToast, setShowToast] = useState(false);
  const [toastMessage, setToastMessage] = useState('');

  const showToastMessage = (message) => {
    setToastMessage(message);
    setShowToast(true);
  };

  const handleSubmit = async (values) => {
    try {
      setLoading(true);
      const response = await networkService.createNetwork(values);
      
      if (response.data.code === 200) {
        showToastMessage('局域网创建成功！');
        // 延迟跳转，让用户看到成功消息
        setTimeout(() => {
          navigate('/network');
        }, 1500);
      } else {
        showToastMessage(response.data.message || '创建失败，请稍后重试');
      }
    } catch (err) {
      if (err.response && err.response.data) {
        showToastMessage(err.response.data.message);
      } else {
        showToastMessage('创建失败，请稍后重试');
      }
    } finally {
      setLoading(false);
    }
  };

  const handleCancel = () => {
    navigate('/network');
  };

  return (
    <MainLayout>
      <div className="create-network-container">
        <div className="create-network-content">
          {/* 页面头部 */}
          <PageHeader />

          {/* 创建表单 */}
          <CreateForm
            onSubmit={handleSubmit}
            onCancel={handleCancel}
            isSubmitting={loading}
          />

          {/* 帮助信息 */}
          <HelpSection />
        </div>
      </div>
      {showToast && (
        <Toast 
          message={toastMessage} 
          onClose={() => setShowToast(false)} 
        />
      )}
    </MainLayout>
  );
};

export default CreateNetwork;